package com.ruoyi.web.controller.api;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.constant.WordType;
import com.ruoyi.stu.domain.StuStudentUnit;
import com.ruoyi.stu.dto.CourseUnitDto;
import com.ruoyi.stu.dto.CourseUnitDto.CourseDto;
import com.ruoyi.stu.dto.CourseUnitDto.CourseFunctionDto;
import com.ruoyi.stu.dto.CourseUnitDto.UnitDto;
import com.ruoyi.stu.enums.StuStudentUnitEnum;
import com.ruoyi.stu.mapper.StuStudentUnitMapper;
import com.ruoyi.system.domain.SysCourse;
import com.ruoyi.system.mapper.SysCourseMapper;

@RestController
@RequestMapping("/api/v1/course")
public class ApiCourseUnitController {
	
    @Autowired
    private SysCourseMapper sysCourseMapper;
    @Autowired
    private StuStudentUnitMapper stuStudentUnitMapper;

    @GetMapping("/units")
    public CourseUnitDto units(@RequestParam Long courseId) {
        // 获取当前登录用户信息
        Long studentId = SecurityUtils.getLoginStudentId();
        
        
        SysCourse sysCourse = sysCourseMapper.selectById(courseId);

        List<CourseFunctionDto> functions = new ArrayList<>();

        // 创建四种功能类型的数据
        String[][] functionTypes = {
            {WordType.STUDY, "单元学习"},
            {WordType.DICTATION, "单元听写"},
            {WordType.WRITING, "单元默写"},
            {WordType.REVIEW, "单元复习"}
        };

        List<StuStudentUnit> listStuStudentUnit = stuStudentUnitMapper.list(studentId, courseId);
        for (String[] functionType : functionTypes) {
        	String type = functionType[0];
        	String name = functionType[1];
            List<UnitDto> listUnitDto = new ArrayList<UnitDto>();
            for(StuStudentUnit e: listStuStudentUnit) {
                Long unitId = e.getUnitId();
                String unitName = e.getUnitName();
                Integer state = WordType.STUDY.equals(type) ? e.getStateStudy()
                		: (WordType.DICTATION.equals(type) ? e.getStateDictation()
                				: (WordType.WRITING.equals(type) ? e.getStateWriting()
                						: e.getStateReview()));
                String status = StuStudentUnitEnum.Complete.getFrontValue(state);
                listUnitDto.add(new UnitDto(unitId, unitName, status));
            }

            CourseFunctionDto function = new CourseFunctionDto(type, name, listUnitDto);
            functions.add(function);
        }

        String courseName = sysCourse.getCourseName();
        CourseDto courseDto = new CourseDto(courseName, courseId, functions);

        CourseUnitDto response = new CourseUnitDto(200, "success", courseDto);
        return response;
    }
}